package cn.conac.rc.ofs.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.conac.rc.framework.service.GenericService;
import cn.conac.rc.ofs.entity.VHistOrgsInfo2Entity;
import cn.conac.rc.ofs.repository.VHistOrgsInfo2Repository;

/**
 * VHistOrgsInfoService类
 *
 * @author serviceCreator
 * @date 2017-02-10
 * @version 1.0
 */
@Service
public class VHistOrgsInfo2Service extends GenericService<VHistOrgsInfo2Entity, Integer> {

	@Autowired
	private VHistOrgsInfo2Repository repository;
	
	public List<VHistOrgsInfo2Entity> findByAreaIdOrderByOrgId(String areaId) {
		return  repository.findByAreaIdOrderByOrgId(areaId);
	}
	
	/**
	 *  包含操作做的用户也包含编办的可能(用户ID间已逗号分隔)
	 * @param orgId
	 * @param areaCode
	 * @return  包含操作做的用户也包含编办的可能
	 */
	public String getWbjUserIdByConditon(Integer orgId, List<VHistOrgsInfo2Entity> VHistOrgsInfo2EntityAllList ) {
		String userIds = null;
		if(null == VHistOrgsInfo2EntityAllList) {
			return userIds;
		}
		List<VHistOrgsInfo2Entity> vHistOrgsInfo2EntityList = new  ArrayList<VHistOrgsInfo2Entity>();
		int findFlag = 0;
		for( VHistOrgsInfo2Entity vHistOrgsInfo2Entity : VHistOrgsInfo2EntityAllList) {
			if(vHistOrgsInfo2Entity.getOrgId().equals(orgId)) {
				vHistOrgsInfo2EntityList.add(vHistOrgsInfo2Entity);
				findFlag = 1;
			} 
			if(findFlag == 1 && !vHistOrgsInfo2Entity.getOrgId().equals(orgId)) {
				break;
			}
		}
		if(vHistOrgsInfo2EntityList.size() == 0) {
			return userIds;
		}
		Set<Integer> userIdList = new  HashSet<Integer>();
		for(VHistOrgsInfo2Entity vHistOrgsInfoEntity : vHistOrgsInfo2EntityList) {
			if(null !=vHistOrgsInfoEntity.getRegUserId()) {
				userIdList.add(vHistOrgsInfoEntity.getRegUserId());
			}
		}
		if(userIdList.size() == 0) {
			return userIds;
		}
		StringBuffer sbUserIds = new StringBuffer();
		Iterator<Integer> userIdsItea = userIdList.iterator();
		while(userIdsItea.hasNext()) {
			sbUserIds.append(userIdsItea.next().toString());
			sbUserIds.append(",");
		}
	    if(StringUtils.isNotEmpty(sbUserIds.toString())) {
	    	userIds = sbUserIds.toString().substring(0, sbUserIds.toString().length() - 1);
	    }
		return userIds;
	}
}
